<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="配置名称" prop="configKey">
                <el-input v-model="queryParams.configKey" placeholder="请输入配置键名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="配置类型" prop="configType">
                <el-select v-model="queryParams.configType" placeholder="请选择配置类型" clearable>
                    <el-option value="text" label="文本" />
                    <el-option value="image" label="图片" />
                    <el-option value="richtext" label="富文本" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd"
                    v-hasPermi="['system:config:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['system:config:edit']">修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                    v-hasPermi="['system:config:remove']">删除</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="configList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="配置ID" align="center" prop="configId" />
            <el-table-column label="配置名称" align="center" prop="configKey" :show-overflow-tooltip="true" />
            <el-table-column label="配置值" align="center" prop="configValue" :show-overflow-tooltip="true">
                <template #default="scope">
                    <span v-if="scope.row.configType === 'image'">
                        <el-image style="max-height: 50px; max-width: 100px;" :src="scope.row.configValue"
                            :preview-src-list="[scope.row.configValue]">
                        </el-image>
                    </span>
                    <span v-else>{{ scope.row.configValue }}</span>
                </template>
            </el-table-column>
            <el-table-column label="配置类型" align="center" prop="configType">
                <template #default="scope">
                    <dict-tag :options="configTypeOptions" :value="scope.row.configType" />
                </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:config:edit']">修改</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['system:config:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改参数配置对话框 -->
        <el-dialog :title="title" v-model="open" width="600px" append-to-body>
            <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="配置名称" prop="configKey">
                    <el-input v-model="form.configKey" placeholder="请输入配置键名" :disabled="form.configId !== undefined" />
                </el-form-item>
                <el-form-item label="配置类型" prop="configType">
                    <el-select v-model="form.configType" placeholder="请选择配置类型">
                        <el-option value="text" label="文本" />
                        <el-option value="image" label="图片" />
                        <el-option value="richtext" label="富文本" />
                    </el-select>
                </el-form-item>
                <el-form-item label="配置值" prop="configValue">
                    <!-- 文本类型 -->
                    <el-input v-model="form.configValue" placeholder="请输入配置值" v-if="form.configType === 'text'" />

                    <!-- 图片类型 -->
                    <div v-else-if="form.configType === 'image'">
                        <el-upload class="avatar-uploader" :action="uploadImgUrl" :headers="headers"
                            :show-file-list="false" :on-success="handleUploadSuccess" :before-upload="beforeUpload">
                            <img v-if="form.configValue" :src="form.configValue" class="avatar">
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </div>

                    <!-- 富文本类型 -->
                    <div v-else-if="form.configType === 'richtext'">
                        <editor v-model="form.configValue" :min-height="200" />
                    </div>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { listConfig, getConfig, addConfig, updateConfig, delConfig } from '@/api/website'
import Editor from '@/components/Editor'
import { getToken } from '@/utils/auth'
import { parseTime } from '@/utils/ruoyi'

const { proxy } = getCurrentInstance()

// 遮罩层
const loading = ref(true)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 参数表格数据
const configList = ref([])
// 弹出层标题
const title = ref("")
// 是否显示弹出层
const open = ref(false)
// 表单参数
const form = ref({})
// 表单校验
const rules = reactive({
    configKey: [
        { required: true, message: "配置键名不能为空", trigger: "blur" }
    ],
    configType: [
        { required: true, message: "配置类型不能为空", trigger: "change" }
    ]
})

// 配置类型数据字典
const configTypeOptions = [
    { value: 'text', label: '文本' },
    { value: 'image', label: '图片' },
    { value: 'richtext', label: '富文本' }
]

// 查询参数
const queryParams = ref({
    pageNum: 1,
    pageSize: 10,
    configKey: undefined,
    configType: undefined
})

// 上传图片地址
const uploadImgUrl = import.meta.env.VITE_APP_BASE_API + '/common/upload'
// 上传图片请求头部
const headers = { Authorization: 'Bearer ' + getToken() }

// 表单引用
const formRef = ref(null)
const queryFormRef = ref(null)

/** 查询参数列表 */
function getList() {
    loading.value = true
    listConfig(queryParams.value).then(response => {
        configList.value = response.rows
        total.value = response.total
        loading.value = false
    })
}

// 取消按钮
function cancel() {
    open.value = false
    reset()
}

// 表单重置
function reset() {
    form.value = {
        configId: undefined,
        configKey: undefined,
        configValue: undefined,
        configType: 'text',
        remark: undefined
    }
    proxy.resetForm("formRef")
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryFormRef")
    handleQuery()
}

/** 选择条目 */
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.configId)
    single.value = selection.length !== 1
    multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
    reset()
    open.value = true
    title.value = "添加网站配置"
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset()
    const configId = row.configId || ids.value[0]
    getConfig(configId).then(response => {
        form.value = response.data
        open.value = true
        title.value = "修改网站配置"
    })
}

/** 提交按钮 */
function submitForm() {
    formRef.value.validate(valid => {
        if (valid) {
            if (form.value.configId !== undefined) {
                updateConfig(form.value).then(response => {
                    ElMessage.success("修改成功")
                    open.value = false
                    getList()
                })
            } else {
                addConfig(form.value).then(response => {
                    ElMessage.success("新增成功")
                    open.value = false
                    getList()
                })
            }
        }
    })
}

/** 删除按钮操作 */
function handleDelete(row) {
    const configIds = row.configId || ids.value
    ElMessageBox.confirm('是否确认删除配置编号为"' + configIds + '"的数据项?').then(() => {
        return delConfig(configIds)
    }).then(() => {
        getList()
        ElMessage.success("删除成功")
    }).catch(() => { })
}

// 图片上传成功处理
function handleUploadSuccess(res) {
    if (res.code === 200) {
        form.value.configValue = res.url
        ElMessage.success("上传成功")
    } else {
        ElMessage.error("上传失败")
    }
}

// 上传前图片格式校验
function beforeUpload(file) {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
    const isLt10M = file.size / 1024 / 1024 < 10

    if (!isJPG) {
        ElMessage.error('上传图片只能是 JPG/PNG/GIF 格式!')
        return false
    }
    if (!isLt10M) {
        ElMessage.error('上传图片大小不能超过 10MB!')
        return false
    }
    return true
}

onMounted(() => {
    getList()
})
</script>

<style scoped>
.avatar-uploader :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader :deep(.el-upload:hover) {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>